'use strict';

const Controller = require('egg').Controller;

class PrizeController extends Controller {
  async list() {
    this.ctx.validate({
      award_type: 'string',
      status: 'string',
      product_type: 'string',
      pageIndex: 'int',
      pageSize: 'int',
    });

    const body = this.ctx.request.body;

    let list = [];
    let total = 0;
    let totalAmount = 0;
    switch (body.award_type) {
      case '1':
        list = await this.ctx.service.prize.list(body);
        total = await this.ctx.service.prize.total(body);
        totalAmount = await this.ctx.service.prize.totalAmount(body);
        break;
      case '2':
        list = await this.ctx.service.prize.list(body);
        total = await this.ctx.service.prize.total(body);
        break;
      case '3':
        list = await this.ctx.service.prize.list(body);
        total = await this.ctx.service.prize.total(body);
      case '4':
        list = await this.ctx.service.prize.list(body);
        total = await this.ctx.service.prize.total(body);
        break;
      case '99':
        list = await this.ctx.service.prize.list(body);
        total = await this.ctx.service.prize.total(body);
        break;
      default:
        break;
    }

    this.ctx.body = {
      code: 0,
      data: {
        list,
        total: total.length > 0 ? total[0].total : 0,
        total_amount: totalAmount.length > 0 ? parseFloat(totalAmount[0].total_amount.toFixed(2)) : 0,
        pageIndex: body.pageIndex,
      },
    };
  }

  async history() {
    const ctx = this.ctx;
    try {
      ctx.validate({
        product_type: 'string',
        status: 'string',
      });

      const body = ctx.request.body;

      const history = await ctx.service.prize.history(body);

      // 优惠券时，去掉金额=0
      const list = history[0].map(item => {
        if (item._id.award_type === '4') {
          item.amount = '';
          return item;
        }
        return item;

      });

      this.ctx.body = {
        code: 0,
        data: {
          list: history[0],
          total: history[1].length > 0 ? history[1][0].total : 0,
          total_amount: history[2].length > 0 ? parseFloat(history[2][0].totalAmount.toFixed(2)) : 0,
          total_quantities: history[2].length > 0 ? history[2][0].totalQuantities : 0,
        },
      };
    } catch (e) {
      ctx.body = {
        code: 1,
        msg: `${e.message}`,
      };
      ctx.logger.error(e);
    }
  }

  // 提交申请
  async mark() {
    this.ctx.validate({
      campaign_id: 'string',
      award_type: 'string',
    });

    const body = this.ctx.request.body;

    const marked = await this.ctx.service.prize.mark(body);

    this.ctx.body = {
      code: 0,
      data: {
        list: marked[0],
        total_amount: marked[1].length > 0 ? Math.floor(marked[1][0].totalAmount*100)/100 : 0,
      },
    };
  }
}

module.exports = PrizeController;
